package com.chatdating.controller;

import com.chatdating.service.BaiduFaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;


import java.io.IOException;
import java.util.Base64;

@RestController
@RequestMapping("/face")
public class BaiduFaceController {

    @Autowired
    private BaiduFaceService baiduFaceService;

    /**
     * 人脸比对接口
     * @return 比对结果 JSON
     */
    @PostMapping("/compare")
    public String compareFaces(@RequestBody Map<String, String> payload)  throws IOException {
        String idCardPhotoBase64 = payload.get("idCardPhoto");
        String facePhotoBase64 = payload.get("facePhoto");
        if (idCardPhotoBase64 == null || facePhotoBase64 == null) {
            return "{\"error\": \"缺少图片参数\"}";
        }
        // 去掉 base64 前缀
        idCardPhotoBase64 = idCardPhotoBase64.split(",")[1];
        facePhotoBase64 = facePhotoBase64.split(",")[1];

        String apiKey = "ZwBCHaq2uIc8qYAiq6TNHINi";
        String secretKey = "QwrHrqy8gBu0mkHp6FFaflUq5XqueoUO";

        // 获取 access_token
        String accessToken = baiduFaceService.getAccessToken(apiKey, secretKey);
        if (accessToken == null || accessToken.isEmpty()) {
            return "{\"error\": \"无法获取 access_token\"}";
        }

        ObjectMapper mapper1 = new ObjectMapper();
        Map<String, String> requestMap1 = new HashMap<>();
        requestMap1.put("image", idCardPhotoBase64);
        requestMap1.put("image_type", "BASE64");

        ObjectMapper mapper2 = new ObjectMapper();
        Map<String, String> requestMap2 = new HashMap<>();
        requestMap2.put("image", facePhotoBase64);
        requestMap2.put("image_type", "BASE64");

        String requestBody1 = mapper1.writeValueAsString(requestMap1);
        String requestBody2 = mapper2.writeValueAsString(requestMap2);
        // 发起人脸比对请求
        return baiduFaceService.sendHttpPostRequest(
                "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" + accessToken,
                requestBody1,requestBody2);
    }

}



